<?php
namespace Modules\User\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use Modules\Order\Entities\BaseOrder as Order;
use Modules\User\Entities\User;

use ThrowException;

class UserGroup extends Model
{
    protected $guarded = [];
    protected $table = 'user_groups';

    protected $casts = [
    	'options' => 'json'
    ];

    static public $resourceName = '用户分组';

    // 计算当前符合条件的mysql语句
    public function getCurrentBuilder($options = NULL)
    {
    	$builder = User::where('id', '>', 0);

    	$options = $options ?: ($this->options ?: []);

    	// 手机号
    	if (@$options['phone']['is_used']) {
    		$builder->whereNotNull('phone');
    	}

    	// 生日
    	if (@$options['birthday']['is_used']) {
    		$builder->whereNotNull('birthday');
    	}

    	// 生日
    	if (@$options['birthday']['is_used']) {
    		$builder->whereNotNull('birthday');
    	}

    	// VIP
    	if (@$options['vip']['is_used']) {
    		$builder->vip();
    	}

    	// 注册时间大于
    	if (@$options['register_time']['is_used']) {
    		$item = @$options['register_time'] ?: [];
    		if (@$item['value']) {
    			$time = date('Y-m-d H:i:s', strtotime('-' . $item['value'] . ' hours'));

    			// 大于小时
    			if ($item['type'] === '>') {
    				$builder->where('created_at', '<', $time);
    			}
    			// 小于小时
    			elseif ($item['type'] === '<') {
    				$builder->where('created_at', '>', $time);
    			}
    			// 小于小时
    			elseif ($item['type'] === '=') {
    				$time2 = date('Y-m-d H:i:s', strtotime('-' . ($item['value'] + 1) . ' hours'));
    				$builder->where('created_at', '<', $time)->where('created_at', '>', $time2);
    			}
    		}
    	}

    	// 用户成长值 
    	if (@$options['level_score']['is_used']) {
    		$item = @$options['level_score'] ?: [];
    		$item['key'] = 'level_score';
    		$builder->assetFilter($item);
    	}

    	// 用户积分
    	if (@$options['score']['is_used']) {
    		$item = @$options['score'] ?: [];
    		$item['key'] = 'score';
    		$builder->assetFilter($item);
    	}

    	// 用户邀请数
    	if (@$options['invitee_total']['is_used']) {
    		$item = @$options['invitee_total'] ?: [];
    		$builder->inviteeTotalFilter($item);
    	}

        // 当日流水数
        if (@$options['today_statement_total']['is_used']) {
            $item = @$options['today_statement_total'] ?: [];

            if (@$item['value']) {
                $t_d = date('Y-m-d');

                $orders = Order::paid()->where([
                    'type' => 'activity',
                    ['completed_at', '>', $t_d],
                    ['user_id', '>', 500]
                ])->whereIn('status', [8,9])
                    ->groupBy('user_id')
                    ->having('amount', '>=', $item['value']*100)
                    ->get(\DB::raw('user_id, sum(redpack_discount + pay_money_price) amount'))
                    ->toArray();

                $user_id = $orders?array_column($orders, 'user_id'):[];
                $builder->whereIn('id', $user_id);
            }
        }

    	return $builder;
    }

    // 计算当前符合条件的用户数量
    public function getUserTotal()
    {
    	return $this->getCurrentBuilder()->count();
    }

    // 某个用户是否符合
    public function isPassed($user)
    {
        return $this->getCurrentBuilder()->where('id', $user->id)->first();
    }

    // 某个用户是否符合
    public function checkRule($user)
    {
        $isPassed = 1;
        $options = $this->options;

        foreach ($options as $key => $item) {
            if ($item['is_used']) {
                $temp = [
                    $key => $item
                ];
                if (!$this->getCurrentBuilder($temp)->where('id', $user->id)->first()) {
                    $isPassed = 0;
                    $options[$key]['is_passed'] = 0;
                }
                else {
                    $options[$key]['is_passed'] = 1;
                }
            }
        }

        return [
            $isPassed,
            $options
        ];
    }
}
